<template>
	<div class="app-container">
		<el-form
			:model="queryParams"
			ref="queryRef"
			:inline="true"
			v-show="showSearch"
			label-width="68px"
		>
			<el-form-item label="项目ID" prop="surveyId">
				<el-input
					v-model="queryParams.surveyId"
					placeholder="请输入项目ID"
					clearable
					@keyup.enter="handleQuery"
				/>
			</el-form-item>
			<el-form-item label="项目名称" prop="surveyTitle">
				<el-input
					v-model="queryParams.surveyTitle"
					placeholder="请输入项目名称"
					clearable
					@keyup.enter="handleQuery"
				/>
			</el-form-item>

			<el-form-item label="公司" prop="companyId">
				<el-select
					v-model="queryParams.companyId"
					placeholder="选择公司"
					style="width: 240px"
				>
					<el-option
						v-for="item in companyList"
						:key="item.id"
						:label="item.companyName"
						:value="item.id"
					/>
				</el-select>
			</el-form-item>

			<el-form-item>
				<el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
				<el-button icon="Refresh" @click="resetQuery">重置</el-button>
			</el-form-item>
		</el-form>

		<ul v-infinite-scroll="load" class="infinite-list" style="overflow: auto">
			<el-table
				v-loading="loading"
				:data="surveyListList"
				@selection-change="handleSelectionChange"
				:default-sort="defaultSort"
				@sort-change="handleSortChange"
				border
			>
				<el-table-column label="标识ID" align="center" prop="id" />
				<el-table-column label="项目ID" align="center" prop="surveyId" />
				<el-table-column label="项目名称" align="center" prop="surveyTitle" />
				<el-table-column label="公司名称" align="center" prop="companyName" />
				<el-table-column label="IR/当前" align="center" prop="surveyIr" />
				<el-table-column label="Loi" align="center" prop="surveyLoi" />
				<el-table-column label="配额" align="center" prop="surveyQuota" />
				<el-table-column
					label="价格"
					align="center"
					prop="surveyPrice"
					sortable="custom"
					:sort-orders="['descending', 'ascending']"
				/>
				<el-table-column label="调查语言/国家" align="center" prop="surveyLanguage" />
				<el-table-column label="点击/完成/配额" align="center" prop="surveyQuotaCount">
					<template #default="scope">
						<span v-html="getFormattedQuotaCount(scope.row.surveyQuotaCount)"></span>
					</template>
				</el-table-column>
				<el-table-column
					label="更新时间"
					align="center"
					prop="surveyTime"
					width="180"
					sortable="custom"
					:sort-orders="['descending', 'ascending']"
				>
					<template #default="scope">
						<span>{{ parseTime(scope.row.surveyTime) }}</span>
					</template>
				</el-table-column>
				<el-table-column label="调查备注" align="center" prop="surveyRemark" />
				<el-table-column label="操作" align="center" class-name="small-padding fixed-width">
					<template #default="scope">
						<el-button-group class="ml-4">
							<el-button
								v-if="scope.row.surveyReady === 0"
								type="danger"
								plain
								disabled
								:icon="Edit"
								@click="handgeturl(scope.row)"
								title="答题链接"
							/>
							<el-button
								v-if="scope.row.surveyReady === 1"
								el-button
								type="primary"
								:icon="Edit"
								@click="handgeturl(scope.row)"
								title="答题链接"
							/>
							<el-button
								type="primary"
								:icon="Brush"
								@click="getstrategy(scope.row)"
								title="攻略"
							/>
						</el-button-group>
					</template>
				</el-table-column>
			</el-table>
		</ul>
		<pagination
			v-show="total > 0"
			:total="total"
			v-model:page="queryParams.pageNum"
			v-model:limit="queryParams.pageSize"
			@pagination="getList"
		/>
		<el-drawer
			v-model="drawer"
			title="调查攻略"
			:direction="direction"
			:before-close="handleClose"
			size="80%"
		>
			<div v-if="forms && forms.specs">
				<p v-if="forms.specs.surveyText" v-html="forms.specs.surveyText"></p>
				<p v-else>暂无攻略</p>
			</div>
			<span v-else>加载中...</span>
		</el-drawer>
	</div>
</template>
<style>
/* 在el-dialog中tinymce z-index 被太小而被遮挡时要加这两句 */
.tox-tinymce-aux {
  z-index: 99999 !important;
}
.tinymce.ui.FloatPanel {
  z-index: 99;
}

.infinite-list {
  height: 800px;
  padding: 0;
  margin: 0;
  list-style: none;
}
.infinite-list .infinite-list-item {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 50px;
  background: var(--el-color-primary-light-9);
  margin: 10px;
  color: var(--el-color-primary);
}
.infinite-list .infinite-list-item + .list-item {
  margin-top: 10px;
}
</style>
<script setup name="SurveyList">
// 获取当前页面的 URL
// 获取当前页面的 URL
const currentUrl = window.location.href;

// 使用正则表达式提取路径部分中的 ID
const match = currentUrl.match(/\/Surveyget\/([^/]+)/);

// 如果匹配成功，获取到 ID
const userkeyid = match ? match[1] : null;

const forms = ref({}); // 使用 ref 创建响应式引用

// 表单重置
function resets() {
  form.value = {}; // 使用 .value 访问和设置响应式引用
  // 可以在这里添加更多的重置逻辑
}

function getstrategy(row) {
  resets(); // 直接调用 reset，无需使用 this
  const _id = row.surveyTitle;
  getSurveystrategyBySurveyTitle(_id).then((response) => {
    forms.value = {
      // 使用 .value 访问和设置响应式引用
      specs: response.data,
    };
    drawer.value = true; // 使用 .value 访问和设置响应式引用
  });
}

import { Edit, Brush } from "@element-plus/icons-vue";
import { listSurveyList, getSurveyUrl } from "@/api/survey/surveyget.js";
import { allListCompany } from "@/api/company/company";
const { proxy } = getCurrentInstance();

const surveyListList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const companyList = ref([]);
const data = reactive({
  form: {},
  form2: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    surveyAddId: null,
    surveyId: null,
    surveyTitle: null,
    surveyIr: null,
    surveyLoi: null,
    surveyQuota: null,
    surveyPrice: null,
    surveyLanguage: null,
    surveyUrl: null,
    surveyTime: null,
    surveyReady: null,
    surveyText: null,
    surveyStrategy: null,
    surveyQuotaCount: null,
    surveyRemark: null,
  },
  rules: {},
});

const { queryParams, form, form2, rules } = toRefs(data);

function getFormattedQuotaCount(surveyQuotaCount) {
  const counts = surveyQuotaCount.split(" / ");
  let formattedCounts = "";
  ``;
  for (let i = 0; i < counts.length; i++) {
    formattedCounts += `<span style="color: ${getStatusColor(i)}">${
      counts[i]
    }</span>`;
    if (i !== counts.length - 1) {
      formattedCounts += " / "; // 添加斜杠分隔符
    }
  }
  return formattedCounts;
}

function getStatusColor(index) {
  if (index === 0) {
    1;
    return "blue"; // 设置第一个数字为蓝色
  } else if (index === 1) {
    return "green"; // 设置第二个数字为绿色
  } else {
    return "red"; // 设置其他数字为红色
  }
}

/** 查询调查列表列表 */
function getList() {
  loading.value = true;
  listSurveyList(queryParams.value, userkeyid).then((response) => {
    surveyListList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    surveyAddId: null,
    surveyId: null,
    surveyTitle: null,
    surveyIr: null,
    surveyLoi: null,
    surveyQuota: null,
    surveyPrice: null,
    surveyLanguage: null,
    surveyUrl: null,
    surveyTime: null,
    surveyReady: null,
    surveyText: null,
    surveyStrategy: null,
    editorContent: null,
    surveyQuotaCount: null,
    surveyRemark: null,
  };
  form2.value = {
    id: null,
    surveyAddId: null,
    surveyId: null,
    surveyTitle: null,
    surveyIr: null,
    surveyLoi: null,
    surveyQuota: null,
    surveyPrice: null,
    surveyLanguage: null,
    surveyUrl: null,
    surveyTime: null,
    surveyReady: null,
    surveyStrategy: null,
    editorContent: null,
    surveyQuotaCount: null,
    surveyRemark: null,
  };
  proxy.resetForm("surveyListRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

const state = reactive({
  user: {},
  roleGroup: {},
  postGroup: {},
});

/** 获取答题链接按钮 */
import axios from "axios"; // 导入axios库
// 定义一个变量来跟踪按钮状态，默认为可点击状态
let isButtonDisabled = false;
async function handgeturl(row) {

  try {

  } catch (error) {
    // 错误处理
    proxy.$message({
      message: "获取失败或项目暂停！",
      type: "error",
    });
    isButtonDisabled = false;
    // 在这里添加错误处理逻辑，例如显示错误消息
    // 例如: proxy.$modal.msgError("操作失败");
  }
  if (isButtonDisabled) {
      return;
    }
    isButtonDisabled = true;
   // 使用async/await异步获取IP地址
   let ipResponse = null;
    try{
      ipResponse = await axios.get("http://api.ipify.org?format=json");
    }catch(error){
      console.log(ipResponse,"ipResponse")
    }
    let ipAddress = null;
    if (!ipResponse) {
        ipAddress = '127.0.0.1';
    }else{
       ipAddress = ipResponse.data.ip;
    }

    // 获取要删除的项的ID
    const _ids = row.surveyTitle || ids.value; // 假设ids.value已经在组件的响应式数据中定义

    // 调用getSurveyUrl函数，传入_ids和ipAddress
    const response = await getSurveyUrl(_ids, ipAddress, userkeyid);
    const surveyUrl = response.data; // Assuming the URL is returned in the 'data' field
    if(surveyUrl){
      // 将URL复制到剪切板
      copyToClipboard(surveyUrl);
        // 显示成功消息
        proxy.$message({
        message: "获取成功！",
        type: "success",
      });
       // 打开新窗口并导航到新地址
      window.open(surveyUrl, "_blank");
    }else{
      // 错误处理
      proxy.$message({
        message: "获取失败或项目暂停！",
        type: "error",
      });
    }
  isButtonDisabled = false;
  getList();
}

function copyToClipboard(text) {
  var textarea = document.createElement("textarea");
  textarea.value = text;
  document.body.appendChild(textarea);
  textarea.select();
  document.execCommand("copy");
  document.body.removeChild(textarea);
}

/** 排序触发事件 */
const defaultSort = ref({ prop: "surveyStartTime", order: "descending" });
function handleSortChange(column, prop, order) {
  queryParams.value.orderByColumn = column.prop;
  queryParams.value.isAsc = column.order;
  getList();
}

/** 查询公司下拉列表 */
function getCompanyList() {
  allListCompany().then(response => {
    console.log(response, "response")
    companyList.value = response.rows;
  });
}
getCompanyList();

getList();

/*关闭右侧弹窗攻略*/
import { ref } from "vue";
import { ElMessageBox } from "element-plus";
import { delSurveyLog } from "@/api/survey/surveyLog.js";
const drawer = ref(false);
const handleClose = (done) => {
  if (typeof done === "function") {
    ElMessageBox.confirm("你确定要关闭攻略吗?")
      .then(() => {
        done();
      })
      .catch(() => {
        // catch error
      });
  } else {
    console.error("Invalid argument: done must be a function");
  }
};

/*调查攻略查询*/
import { getSurveystrategyBySurveyTitle } from "@/api/survey/surveystrategy";
</script>
